package com.zysc.processflow.controller;


import com.zysc.processflow.common.base.ResultBody;
import com.zysc.processflow.common.util.StringUtils;
import com.zysc.processflow.entity.*;
import com.zysc.processflow.service.IOrganizationService;
import com.zysc.processflow.service.IPersonService;
import com.zysc.processflow.service.IPersonorgService;
import com.zysc.processflow.service.IPersonroleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import com.zysc.processflow.common.base.BaseController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 人员单位关系表 前端控制器
 * </p>
 *
 * @author 正元智慧城市_
 * @since 2023-01-06
 */
@Api(value = "人员和单位关系表", tags = "人员和单位关系表")
@RestController
@RequestMapping("/personorg")
public class PersonorgController extends BaseController<Personorg> {

    @Autowired
    IPersonorgService service;
    @Autowired
    IPersonService personService;
    @Autowired
    IPersonroleService personroleService;
    @Autowired
    IOrganizationService organizationService;
    public PersonorgController(IPersonorgService service) {
        super(service);
    }

    private static Logger logger = LoggerFactory.getLogger(PersonorgController.class);

    @ApiOperation("获取人员和单位的关系数据")
    @GetMapping(value = "getpersonorgListByPersonidAndOrgid")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "人员id", name = "personid", dataType = "String"),
            @ApiImplicitParam(value = "单位id", name = "orgid", dataType = "String")
    })
    public ResultBody getpersonorgListByPersonidAndOrgid(String personid,String orgid) {
        List<Personorg> list = service.getpersonorgListByPersonidAndOrgid(personid,orgid);
        return ResultBody.Success(list);
    }


    @ApiOperation("添加/更新人员-单位关系信息")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "人员-单位关系信息", name = "entity", dataType = "Personorg")
    })
    @Transactional
    @PostMapping(value = "SaveOrUpdate")
    public ResultBody SaveOrUpdate(@RequestBody Personorg entity) {
        try{
            Boolean b = service.saveOrUpdatePersonorgInfo(entity);
            if(!b){
                throw new RuntimeException("保存人员-单位关系信息失败!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultBody.error(e.getMessage(), 500);
        }
        return ResultBody.Success(entity);
    }


    @ApiOperation("删除用户单位关系")
    @PostMapping("DeletePersonorg")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "人员单位关系实体", name = "entity", dataType = "Personorg")
    })
    public ResultBody DeletePersonorg(@RequestBody Personorg entity) {
        try{
            Boolean b = service.DeletePersonorg(entity);
            if(!b){
                throw new RuntimeException("删除人员信息失败!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultBody.error(e.getMessage(), 500);
        }
        return ResultBody.Success(entity);
    }

    @ApiOperation("导入人员")
    @PostMapping("importPersonOrgList")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "人员单位关系实体", name = "map", dataType = "Map")
    })
    public ResultBody importPersonOrgList(@RequestBody List<Map> list) {
        System.out.println(list);
        List<Person> personList = new ArrayList<>();
        List<Personorg> personorgList = new ArrayList<>();
        List<Personrole> personroleList = new ArrayList<>();
        list.forEach(item->{
            String code = item.get("code").toString().trim();
            Organization organization = organizationService.getOrganizationFromAll(code);
            if(organization==null){
                logger.error("未找到单位,"+code);
            }else{
                if(organization.getIsdel()!=0){
                    organizationService.setIsDelByTyshxydm(code);
                }
                //1.生成三条人员信息
                String securename = item.getOrDefault("securename","").toString().trim();
                String securephone = item.getOrDefault("securephone","").toString().trim();
                String productionname = item.getOrDefault("productionname","").toString().trim();
                String productionphone = item.getOrDefault("productionphone","").toString().trim();
                String mainname = item.getOrDefault("mainname","").toString().trim();
                String mainphone = item.getOrDefault("mainphone","").toString().trim();

                Person person1 = new Person();
                person1.setId("excelimport"+ UUID.randomUUID().toString());
                person1.setName(securename);
                person1.setPhone(securephone);
                person1.setCreator("excel导入");

                Person person2 = new Person();
                person2.setId("excelimport"+ UUID.randomUUID().toString());
                person2.setName(productionname);
                person2.setPhone(productionphone);
                person2.setCreator("excel导入");

                Person person3 = new Person();
                person3.setId("excelimport"+ UUID.randomUUID().toString());
                person3.setName(mainname);
                person3.setPhone(mainphone);
                person3.setCreator("excel导入");

                personList.add(person1);
                personList.add(person2);
                personList.add(person3);

                //2.生成一条人员机构关系信息
                Personorg personorg1 = new Personorg();
                personorg1.setId("excelimport"+ UUID.randomUUID().toString());
                personorg1.setCreator("excel导入");
                personorg1.setOrgid(organization.getId());
                personorg1.setOrgname(organization.getName());
                personorg1.setPersonid(person1.getId());
                personorg1.setPersonname(person1.getName());

                Personorg personorg2 = new Personorg();
                personorg2.setId("excelimport"+ UUID.randomUUID().toString());
                personorg2.setCreator("excel导入");
                personorg2.setOrgid(organization.getId());
                personorg2.setOrgname(organization.getName());
                personorg2.setPersonid(person2.getId());
                personorg2.setPersonname(person2.getName());

                Personorg personorg3 = new Personorg();
                personorg3.setId("excelimport"+ UUID.randomUUID().toString());
                personorg3.setCreator("excel导入");
                personorg3.setOrgid(organization.getId());
                personorg3.setOrgname(organization.getName());
                personorg3.setPersonid(person3.getId());
                personorg3.setPersonname(person3.getName());

                if(!StringUtils.isNull(personorg1.getPersonid()) && !StringUtils.isNull(personorg1.getOrgid())){
                    personorgList.add(personorg1);
                }
                if(!StringUtils.isNull(personorg2.getPersonid()) && !StringUtils.isNull(personorg2.getOrgid())){
                    personorgList.add(personorg2);
                }
                if(!StringUtils.isNull(personorg3.getPersonid()) && !StringUtils.isNull(personorg3.getOrgid())){
                    personorgList.add(personorg3);
                }
                //3.生成一条人员角色关系信息
                Personrole personrole1 = new Personrole();
                personrole1.setId("excelimport"+ UUID.randomUUID().toString());
                personrole1.setCreator("excel导入");
                personrole1.setPersonid(person1.getId());
                personrole1.setPersonname(person1.getName());
                personrole1.setRoleid("processflow_security");
                personrole1.setRolename("企业安全管理机构负责人");

                Personrole personrole2 = new Personrole();
                personrole2.setId("excelimport"+ UUID.randomUUID().toString());
                personrole2.setCreator("excel导入");
                personrole2.setPersonid(person2.getId());
                personrole2.setPersonname(person2.getName());
                personrole2.setRoleid("processflow_productionwork");
                personrole2.setRolename("企业分管生产工作的公司领导");

                Personrole personrole3 = new Personrole();
                personrole3.setId("excelimport"+ UUID.randomUUID().toString());
                personrole3.setCreator("excel导入");
                personrole3.setPersonid(person3.getId());
                personrole3.setPersonname(person3.getName());
                personrole3.setRoleid("processflow_mainmanager");
                personrole3.setRolename("企业主要负责人");
                personroleList.add(personrole1);
                personroleList.add(personrole2);
                personroleList.add(personrole3);
            }
        });

        boolean b = personService.saveOrUpdateBatch(personList);
        boolean b1 = personroleService.saveOrUpdateBatch(personroleList);
        boolean b2 = service.saveOrUpdateBatch(personorgList);

        return ResultBody.Success(b1&&b2&&b);
    }

    @ApiOperation("导入值班人员")
    @PostMapping("importDutyPersonList")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "人员单位关系实体", name = "map", dataType = "Map")
    })
    public ResultBody importDutyPersonList(@RequestBody List<Map> list) {
        List<Person> personList = new ArrayList<>();
        List<Personorg> personorgList = new ArrayList<>();
        List<Personrole> personroleList = new ArrayList<>();
        list.forEach(item->{
            if(item.get("code")==null){
                logger.error("null aaaaa,"+item);
            }
            String code = item.get("code").toString().trim();
            Organization organization = organizationService.getOrganizationFromAll(code);
            if(organization==null){
                logger.error("未找到单位,"+code);
            }else{
                List<Person> processflowDisposer = personService.getPersonListByOrgIdAndRoleId(code, "processflow_disposer");
                if(processflowDisposer.size() == 0){//只有没人的话才新增
                    //1.生成三条人员信息
                    String dutyname = "值班人员";
                    String dutyphone = item.getOrDefault("dutyphone","").toString().trim();
                    Person person = new Person();
                    person.setId("excelimportdisposer"+ UUID.randomUUID().toString());
                    person.setName(dutyname);
                    person.setPhone(dutyphone);
                    person.setCreator("excel导入disposer");

                    //新增虚拟人员
                    logger.info("新增虚拟人员(值班人员):电话为:"+dutyphone);
                    personList.add(person);

                    //2.生成一条人员机构关系信息
                    Personorg personorg1 = new Personorg();
                    personorg1.setId("excelimportdisposer"+ UUID.randomUUID().toString());
                    personorg1.setCreator("excel导入disposer");
                    personorg1.setOrgid(organization.getId());
                    personorg1.setOrgname(organization.getName());
                    personorg1.setPersonid(person.getId());
                    personorg1.setPersonname(person.getName());

                    if(!StringUtils.isNull(personorg1.getPersonid()) && !StringUtils.isNull(personorg1.getOrgid())){
                        personorgList.add(personorg1);
                    }
                    //3.生成一条人员角色关系信息
                    Personrole personrole1 = new Personrole();
                    personrole1.setId("excelimportdisposer"+ UUID.randomUUID().toString());
                    personrole1.setCreator("excel导入disposer");
                    personrole1.setPersonid(person.getId());
                    personrole1.setPersonname(person.getName());
                    personrole1.setRoleid("processflow_disposer");
                    personrole1.setRolename("报警处置人");

                    personroleList.add(personrole1);
                }
            }
        });

        boolean b = personService.saveOrUpdateBatch(personList);
        boolean b1 = personroleService.saveOrUpdateBatch(personroleList);
        boolean b2 = service.saveOrUpdateBatch(personorgList);

        return ResultBody.Success(null);
    }
}
